import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { base, ajax, toast, createPage } from 'nc-lightapp-front';
import { initTemplate, afterEvent, searchClick } from './events';
import { setForm } from 'src/erm/sscrppublic/common/utils/setComponentUsed';
import requestApi from './requestApi'
import './index.less';
import _ from 'lodash-es';

window.pageCode = {
    searchPage: '201102621_2621_IWEB'
};
window.fyytAreaCode = {
    searchArea: 'search',
    billsArea: 'head',
    bodysArea: 'accrued_detail'
};

export default class Fyyt extends Component {
    constructor(props) {
        super(props);
        setForm(props, window.fyytAreaCode.searchArea)
        this.state = {
            showFyytModal: true,

        }
        let { form, button, table, editTable, search } = this.props;
        let { setSearchValue, setSearchValByField, getAllSearchData } = search;
        this.setSearchValByField = setSearchValByField;//设置查询区某个字段值
        this.getAllSearchData = getAllSearchData;//获取查询区所有字段数据
        this.isError = false; //转单编辑后字段是否通过验证

        if (this.props.showFyytModal) {
            initTemplate.call(this, props);
        }
    }
    setTransferBtnDisabled(flag) {
        //设置“冲借款”按钮是否可用
        // let btnObj = document.querySelector('.area-right .main-button');
        let spanObj = document.querySelector('.area-right .wui-button-text-wrap'); // 平台按钮元素更改，获取方式更改 
        let btnObj = document.querySelector('.area-right .nc-button-wrapper'); // 平台按钮元素更改，获取方式更改 
        if (flag == true) {
            spanObj&&spanObj.setAttribute('disabled', true);
        } else {
            spanObj&&spanObj.removeAttribute('disabled');
            btnObj&&btnObj.removeAttribute('disabled');
        }

    }

    componentDidMount() {
        //设置“冲借款”按钮在不勾选任何数据的时候也可用，添加监听 begin
        /* let that = this;
        var time = setInterval(() => {
            let btnObj = document.querySelector('.area-right .main-button');
            if (btnObj) {
                clearInterval(time);
                btnObj.addEventListener('click', function () {
                    //判断是否有已选的条目，有就直接return， 无则继续执行逻辑
                    let selectdata = that.props.transferTable.getTransferTableSelectedValue()
                    if (selectdata != undefined && selectdata.head != undefined && selectdata.head.length > 0) {
                        return;
                    }
                    window.pageFyytClick(null);
                })
            }
        }, 300) */
        //end
        this.props.transferTable.setTransferTableValue(window.fyytAreaCode.billsArea, window.fyytAreaCode.bodysArea, [], 'pk_accrued_bill', 'pk_accrued_detail');
    }

    render() {
        let { form, button, table, editTable, search, transferTable } = this.props;
        let { NCCreateSearch } = search;
        let { createButton } = button;
        let { createEditTable } = editTable;
        let { createTransferTable } = transferTable;
        let tradetype = this.props.getUrlParam("tradetype");
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        return (
            // "201102BCLF-0013": "预提单",
            <div className="nc-single-table" style = {{backgroundColor:'#e0e4ec'}}>

                {/*
                <div className="title">{multiLang && multiLang.get('201102BCLF-0013')}</div>
            <div className="header">

            </div>
            <div className="content-wrap">
                <div className="bar">

                </div>
            </div>
            */}

                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(
                        window.fyytAreaCode.searchArea,//模块id
                        {
                            clickPlanEve: searchClick.bind(this),//点击高级面板中的查询方案事件
                            clickSearchBtn: searchClick.bind(this),//   点击按钮事件
                            defaultConditionsNum: 1, //默认显示几个查询条件
                            onAfterEvent: afterEvent()//编辑后事件
                        }
                    )}
                </div>
                <div className="nc-singleTable-table-area" >
                    {createTransferTable(
                        {
                            editStatus: true,
                            headTableId: window.fyytAreaCode.billsArea,//表格组件id
                            bodyTableId: window.fyytAreaCode.bodysArea,//子表模板id
                            fullTableId: window.fyytAreaCode.bodysArea,//主子拉平模板id
                            //点击加号展开，设置表格数据
                            // "201102BCLF-0003": "核销预提",
                            transferBtnText: multiLang && multiLang.get('201102BCLF-0003'), //转单按钮显示文字
                            containerSelector: '#fyyttransfer', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                            cacheItem: ['verify_amount', "pk_accrued_bill", "pk_accrued_detail", "billno", "pk_iobsclass", "rest_amount"], //缓存字段
                            editableItem: ['verify_amount'], //可编辑字段
                            afterEvent: (attrcode, value, record, index, oldvalue) => {
                                console.log('编辑后事件', attrcode, value, record, index, oldvalue);
                                //debugger;
                                switch (attrcode) {
                                    case 'verify_amount':
                                        let scale = record.verify_amount.scale
                                        if( parseFloat(value).toFixed(scale) === parseFloat("0.00").toFixed(scale)) return ; // 如果输入金额为0
                                        let selectrowbody = this.props.transferTable.getTransferTableSelectedValue(); // 获取选中的值
                                        let pk_bzbm = _.get(selectrowbody,'head[0].head.head.rows[0].values.pk_currtype.value', '') || window.defaultBzbm
                                        if( window.hxytMap.has(pk_bzbm)){ 
                                            // 这里要比较剩余核销金额数和输入的数值（value） 以及 当前核销金额（predict_rest_amount）的值与剩余额度的值
                                            let inputValue = parseFloat(value);
                                            let currentPredictAmount = parseFloat(oldvalue);
                                            // 比较当前输入的金额与当前和预计余额（ predict_rest_amount ）
                                            if( inputValue > currentPredictAmount ){
                                                toast({ content: multiLang && multiLang.get('201102BCLF-0011'), color: 'danger' });
                                                // this.isError = true;
                                                // 重新设置当前
                                                record['verify_amount'] = {...record['verify_amount'],display:currentPredictAmount.toFixed(scale), scale:scale ,value: currentPredictAmount.toFixed(scale)} // 取消后核销金额设置为0
                                                this.props.transferTable.setRowDataByIndex('head', record, record.rowIndex);
                                                // 重置表头额度
                                                this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { value: currentPredictAmount, scale, display: currentPredictAmount} }, record.parentRowId || record.headKey);
                                            }else{
                                                //输入额度小于当前核销额度，

                                                //重新计算剩余额度 额度+差值
                                                let bxye = parseFloat(window.hxytMap.get(pk_bzbm)); 
                                                let mult = Math.pow(10, scale)
                                                let subNum = parseFloat((+currentPredictAmount*mult - +inputValue*mult)/mult).toFixed(scale)
                                                //debugger;
                                                let bxye_new = Number(bxye) + Number(subNum);
                                                window.hxytMap.delete(pk_bzbm);
                                                //debugger;

                                                window.hxytMap.set(pk_bzbm, bxye_new);//重置核销余额
                                                record['verify_amount'] = {...record['verify_amount'],display:inputValue.toFixed(scale), scale:scale ,value: inputValue.toFixed(scale)} // 取消后核销金额设置为0
                                                this.props.transferTable.setRowDataByIndex('head', record, record.rowIndex);
                                                // 重置表头数据
                                                let total = 0.00;
                                                let selectrow = this.props.transferTable.getTransferTableSelectedValue();
                                                // debugger;
                                                selectrow && selectrow.head.length && selectrow.head[0].body.accrued_detail.rows.forEach((row) => {
                                                    total = parseFloat(total) + parseFloat(row.values.verify_amount.value);
                                                });
                                                this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { value: total, scale, display:total } }, record.parentRowId || record.headKey);
                                                
                                            }
                                        }

                                        //if (value > record.verify_amount.value) { //这里写具体的业务判断条件
                                        // "201102BCLF-0011": "修改失败，输入的金额有误",
                                        // if (parseFloat(value) > parseFloat(record.predict_rest_amount.value)) {
                                        //     toast({ content: multiLang && multiLang.get('201102BCLF-0011'), color: 'danger' });
                                        //     this.isError = true;
                                        // } else {
                                        //     this.isError = false;
                                        //     let scale = record.predict_rest_amount.value.split('.')[1].length;
                                        //     let total = 0;
                                        //     //计算表头核销金额
                                        //     let selectrow = this.props.transferTable.getTransferTableSelectedValue();
                                        //     selectrow && selectrow.head.length && selectrow.head[0].body.accrued_detail.rows.forEach((row) => {
                                        //         total = parseFloat(total) + parseFloat(row.values.verify_amount.value);
                                        //     });
                                        //     this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { value: total, scale } }, record.parentRowId || record.headKey);
                                        // }
                                        break;
                                }
                            }, //编辑后事件
                            onTransferBtnClick: (ids) => {//点击转单按钮钩子函数
                                // "201102BCLF-0011": "修改失败，输入的金额有误",
                                if (this.isError) {
                                    toast({ content: multiLang && multiLang.get('201102BCLF-0011'), color: 'danger' });
                                } else {

                                    window.pageFyytClick(ids);

                                }

                            },
                            onCheckedChange: (flag, record, index, bodys) => {
                                if( index === 'all') return; // 第一次是全选，然后当前页面所有的表头都会重新进入
                                this.setTransferBtnDisabled(false)
                                // debugger;
								//bodys有值为 body选中 bodys没值为head选中  flag代表选中状态                                
								console.log('checked:',event, flag, record, index, bodys)
								let tableData = this.props.transferTable.getTransferTableValue('head')
								console.log('checked:', tableData)
                                let scale = record.predict_rest_amount.scale || '3'
                                let pk_bzbm = '';
                                let bzbm = '';
                                let checkedPk = record.parentRowId || '' //子表PK

                                let selectrowbody = this.props.transferTable.getTransferTableSelectedValue(); // 获取所有勾选的值
                                // debugger;
                                if (selectrowbody.head && selectrowbody.head.length > 0) {
                                    selectrowbody.head.forEach((item) => { // 计算当前子项的和  pk_accrued_bill 预提单pk
                                        let currentPkType = _.get(item, 'head.head.rows[0].values.pk_accrued_bill.value', ''); // 当前主表ID
                                        if( currentPkType && checkedPk === checkedPk ){ // 查找当前主表
                                            pk_bzbm = _.get(item, 'head.head.rows[0].values.pk_currtype.value', '')
                                            bzbm = _.get(item, 'head.head.rows[0].values.pk_currtype.value', '')
                                        }
                                    });
                                }else{
                                    pk_bzbm = window.defaultBzbm;
                                    bzbm = window.defaultBzbm;
                                }
                                    
                                

								if (index !== 'all') {
									this.setTransferBtnDisabled(false)
									let datas = [];
									//是否是表头的切换选中事件
									if (record.parentRowId) {
										datas[0] = record									
									} else if (bodys && bodys.length > 0) {
										datas = bodys;
									}

                                    if (flag == true) { // 选中当前行    
                                        datas.forEach((data) => {                         
                                            if (window.hxytMap.has(pk_bzbm)) { //币种编码 
                                                // bxye 按照币种获取报销金额 
                                                let bxye = parseFloat(window.hxytMap.get(pk_bzbm)); //原始金额
                                                let scala = data.predict_rest_amount&&data.predict_rest_amount.scale || '4' 
                                                let  bxye_new = ''
                                                if (bxye - parseFloat(data.predict_rest_amount.value) > 0) { // 如果额度大于当前选中预计余额数据
                                                    data['verify_amount'] =  {... data['verify_amount'],display:data['predict_rest_amount'].value, value:data['predict_rest_amount'].value, scale:scala} //data['yjye'].value;
                                                    bxye_new = (bxye - parseFloat(data['predict_rest_amount'].value)).toFixed(scala);//重新计算余额，重要
                                                    window.hxytMap.delete(pk_bzbm);
                                                    window.hxytMap.set(pk_bzbm, bxye_new);//重置报销余额
                                                } else { // 金额小于单据列表选中金额, 核销预提额度为0
                                                    let bxye = parseFloat(window.hxytMap.get(pk_bzbm)); //原始金额
                                                    bxye_new = bxye;//计算剩余插值
                                                    data['verify_amount'] = {... data['verify_amount'],display:parseFloat(bxye_new).toFixed(scala), scale:scala, value: parseFloat(bxye_new).toFixed(scala)};
                                                    
                                                    window.hxytMap.delete(pk_bzbm);
                                                    window.hxytMap.set(pk_bzbm, parseFloat('0.00').toFixed(scala));//重置核销预提余额
                                                }
                                                console.log('bxye_new', bxye_new)
                                                this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                                // this.props.transferTable.updateHeadRowByKey(
                                                //     'head',
                                                //     { verify_amount: { scale: scale, value: bxye_new, display: bxye_new } },
                                                //     record.parentRowId || record.headKey
                                                // )
                                            }
                                        })
                                    }
                                    else if(flag == false){ // 取消选中, 重新计算核销预提额度
                                        datas.forEach((data) => {
                                            let scala = data.predict_rest_amount&&data.predict_rest_amount.scale||'4'; // 核销预提原金额精度
                                            let bxye_new_cancle = parseFloat(window.hxytMap.get(bzbm)) + parseFloat(data['verify_amount'].value);//重新计算报销余额，重要
                                            window.hxytMap.delete(bzbm);
                                            window.hxytMap.set(bzbm, bxye_new_cancle.toFixed(2));//重置核销预提余额

                                            data['verify_amount'] = {...data['verify_amount'],display:parseFloat("0.00").toFixed(scala), scale:scala ,value: parseFloat("0.00").toFixed(scala)} // 取消后核销金额设置为0
                                            this.props.transferTable.setRowDataByIndex('head', data, data.rowIndex);
                                            // this.props.transferTable.updateHeadRowByKey(
                                            //     'head',
                                            //     { verify_amount: { scale: scale, value: parseFloat("0.00").toFixed(scala) } },
                                            //     record.parentRowId || record.headKey
                                            // )
                                        });
                                    }
                                    
                                    let hkybje_sethead =0.00; // 重新计算非子项核销预提的值
                                    let selectrowbody = this.props.transferTable.getTransferTableSelectedValue(); // 获取所有勾选的值

                                    if (selectrowbody.head && selectrowbody.head.length > 0) {
                                        selectrowbody.head.forEach((item) => { // 计算当前子项的和  pk_accrued_bill 预提单pk
                                            let currentPk = _.get(item, 'head.head.rows[0].values.pk_accrued_bill.value', '');
                                            let introPk = _.get(record, 'pk_accrued_bill.value', ''); //传入的pk
                                            if( currentPk && introPk && currentPk === introPk ){ // 这边应该计算的是当前选择的和传入的数据是一个明细时,执行加法操作
                                                if(item.body.accrued_detail.rows.length >=1 ){
                                                    item.body.accrued_detail.rows.forEach(row => {
                                                        hkybje_sethead += Number(row.values.verify_amount.value) // 这里有点问题
                                                    })
                                                    this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { display: String(hkybje_sethead.toFixed(scale)), scale, value: String(hkybje_sethead.toFixed(scale)) } }, record.parentRowId || record.headKey);
                                                }
                                            }else{
                                                this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { display: String(0.00.toFixed(scale)), scale, value: String(0.00.toFixed(scale)) } }, record.parentRowId || record.headKey);
                                            }
                                        });
                                        this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { display: String(hkybje_sethead.toFixed(scale)), scale, value: String(hkybje_sethead.toFixed(scale)) } }, record.parentRowId || record.headKey);
                                    }else{
                                        this.props.transferTable.updateHeadRowByKey('head', { "verify_amount": { display: String(0.00.toFixed(scale)), scale, value: String(0.00.toFixed(scale)) } }, record.parentRowId || record.headKey);
                                    }
                                   
								}
								
							},
                            onChangeViewClick: () => {//点击切换视图钩子函数
                                if (!this.props.meta.getMeta()[window.fyytAreaCode.bodysArea]) {
                                    initTemplate.call(this, this.props); //加载主子拉平模板
                                }
                                this.props.transferTable.changeViewType(this.headTableId);

                            }
                        }
                    )}
                </div>
            </div>

        )
    }
}

Fyyt = createPage({
    mutiLangCode: '2011'
})(Fyyt);

ReactDOM.render(<Fyyt />, document.querySelector('#app'));
